import { userlogin } from "@/api/user.js";
import { Message } from "element-ui";
import router from "@/router";
const state = {
  token: localStorage.getItem("token") || "",
  userinfo: {
    grade: "",
    name: "",
    phone: "",
    roleid: "",
    studentid: "",
  },
  user: null,
};

const mutations = {
  SET_TOKEN(state, token) {
    localStorage.setItem("token", token);
    state.token = token;
  },
  CLEAR_TOKEN(state) {
    state.token = "";
    localStorage.removeItem("token");
  },
  SET_GRADE(state, grade) {
    state.userinfo.grade = grade;
  },
  SET_NAME(state, name) {
    state.userinfo.name = name;
  },
  SET_PHONE(state, phone) {
    state.userinfo.phone = phone;
  },
  SET_ROLEID(state, roleid) {
    state.userinfo.roleid = roleid;
  },
  SET_STUDENTID(state, studentid) {
    state.userinfo.studentid = studentid;
  },
};

const actions = {
  async login({ commit }, { username, password }) {
    const res = await userlogin(username, password);
    if (res.status === true && res.token) {
      commit("SET_TOKEN", res.token);
      Message({
        message: "登录成功！",
        type: "success",
      });
      router.push("/");
    }
    return res;
  },
  logout({ commit }) {
    commit("CLEAR_TOKEN");
    commit("SET_GRADE", "");
    commit("SET_NAME", "");
    commit("SET_PHONE", "");
    commit("SET_ROLEID", "");
    commit("SET_STUDENTID", "");
  },
  // { commit },
  async getUserinfo() {
    // console.log(res);
  },
  async updateUserInfo({ dispatch, getters }) {
    // console.log(userfrom);
    const currentToken = getters.gettoken;
    await dispatch("getUserinfo", currentToken);
    return;
  },
};

const getters = {
  // localStorage.getItem("token")
  gettoken(state) {
    return state.token;
  },
  getuser(state) {
    return state.userinfo;
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
